<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Timeline,
} from 'ant-design-vue';

const loading = ref(false);
const logList = ref<any[]>([]);
const selectedRowKeys = ref<string[]>([]);

const searchForm = reactive({
  keyword: '',
  operationType: '',
  user: '',
  dateRange: [],
  status: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 操作类型选项
const operationTypeOptions = [
  { label: '登录', value: 'LOGIN' },
  { label: '登出', value: 'LOGOUT' },
  { label: '创建', value: 'CREATE' },
  { label: '编辑', value: 'EDIT' },
  { label: '删除', value: 'DELETE' },
  { label: '查询', value: 'QUERY' },
  { label: '导出', value: 'EXPORT' },
  { label: '权限变更', value: 'PERMISSION_CHANGE' },
];

// 状态选项
const statusOptions = [
  { label: '成功', value: 'SUCCESS' },
  { label: '失败', value: 'FAILED' },
  { label: '异常', value: 'ERROR' },
];

// 表格列定义
const columns = [
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 180,
  },
  {
    title: '用户',
    dataIndex: 'user',
    key: 'user',
    width: 120,
  },
  {
    title: '操作类型',
    dataIndex: 'operationType',
    key: 'operationType',
    width: 120,
  },
  {
    title: '模块',
    dataIndex: 'module',
    key: 'module',
    width: 120,
  },
  {
    title: '操作描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
  },
  {
    title: 'IP地址',
    dataIndex: 'ipAddress',
    key: 'ipAddress',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right' as const,
  },
];

// 加载日志数据
const loadLogs = async () => {
  loading.value = true;
  try {
    // 模拟日志数据
    const mockLogs = [
      {
        id: '1',
        timestamp: '2024-03-15 14:30:25',
        user: 'admin',
        operationType: 'LOGIN',
        module: '系统登录',
        description: '用户登录系统',
        ipAddress: '192.168.1.100',
        status: 'SUCCESS',
        details: {
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
          sessionId: 'session_123456',
        },
      },
      {
        id: '2',
        timestamp: '2024-03-15 14:35:12',
        user: 'admin',
        operationType: 'CREATE',
        module: '资源目录',
        description: '创建新资源：豪华套房',
        ipAddress: '192.168.1.100',
        status: 'SUCCESS',
        details: {
          resourceId: 'RES_001',
          resourceName: '豪华套房',
          resourceType: 'ROOM',
        },
      },
      {
        id: '3',
        timestamp: '2024-03-15 14:40:08',
        user: 'resource_manager',
        operationType: 'EDIT',
        module: '排期管理',
        description: '修改排期：会议室A',
        ipAddress: '192.168.1.101',
        status: 'SUCCESS',
        details: {
          scheduleId: 'SCH_001',
          oldValue: { startTime: '09:00', endTime: '10:00' },
          newValue: { startTime: '09:30', endTime: '10:30' },
        },
      },
      {
        id: '4',
        timestamp: '2024-03-15 14:45:33',
        user: 'finance_user',
        operationType: 'QUERY',
        module: '占用结算',
        description: '查询结算报表',
        ipAddress: '192.168.1.102',
        status: 'SUCCESS',
        details: {
          queryParams: { dateRange: '2024-03-01 to 2024-03-15' },
          resultCount: 156,
        },
      },
      {
        id: '5',
        timestamp: '2024-03-15 14:50:17',
        user: 'maintenance_user',
        operationType: 'DELETE',
        module: '维护管理',
        description: '删除维护计划：空调维护',
        ipAddress: '192.168.1.103',
        status: 'SUCCESS',
        details: {
          maintenanceId: 'MAINT_001',
          reason: '计划调整',
        },
      },
      {
        id: '6',
        timestamp: '2024-03-15 14:55:42',
        user: 'admin',
        operationType: 'PERMISSION_CHANGE',
        module: '权限管理',
        description: '为用户 finance_user 分配新角色',
        ipAddress: '192.168.1.100',
        status: 'SUCCESS',
        details: {
          userId: 'finance_user',
          oldRole: 'USER',
          newRole: 'FINANCE',
        },
      },
      {
        id: '7',
        timestamp: '2024-03-15 15:00:15',
        user: 'unknown_user',
        operationType: 'LOGIN',
        module: '系统登录',
        description: '尝试登录失败',
        ipAddress: '192.168.1.200',
        status: 'FAILED',
        details: {
          reason: '用户名或密码错误',
          attempts: 3,
        },
      },
      {
        id: '8',
        timestamp: '2024-03-15 15:05:28',
        user: 'admin',
        operationType: 'EXPORT',
        module: '数据分析',
        description: '导出资源使用报表',
        ipAddress: '192.168.1.100',
        status: 'SUCCESS',
        details: {
          reportType: 'resource_usage',
          format: 'Excel',
          recordCount: 1256,
        },
      },
    ];

    logList.value = mockLogs;
    pagination.total = mockLogs.length;
  } catch (error) {
    console.error('加载日志数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadLogs();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    operationType: '',
    user: '',
    dateRange: [],
    status: '',
  });
  handleSearch();
};

// 查看详情
const viewDetail = (record: any) => {
  Modal.info({
    title: '操作详情',
    width: 600,
    content: `
      <div style="padding: 16px;">
        <p><strong>时间：</strong>${record.timestamp}</p>
        <p><strong>用户：</strong>${record.user}</p>
        <p><strong>操作类型：</strong>${getOperationTypeLabel(record.operationType)}</p>
        <p><strong>模块：</strong>${record.module}</p>
        <p><strong>描述：</strong>${record.description}</p>
        <p><strong>IP地址：</strong>${record.ipAddress}</p>
        <p><strong>状态：</strong>${getStatusLabel(record.status)}</p>
        <p><strong>详细信息：</strong></p>
        <pre style="background: #f5f5f5; padding: 8px; border-radius: 4px;">${JSON.stringify(record.details, null, 2)}</pre>
      </div>
    `,
  });
};

// 导出日志
const exportLogs = () => {
  console.log('导出日志');
  // 这里可以实现日志导出功能
};

// 批量删除
const batchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    return;
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 条日志记录吗？`,
    onOk: () => {
      logList.value = logList.value.filter(
        (log) => !selectedRowKeys.value.includes(log.id),
      );
      selectedRowKeys.value = [];
      message.success('删除成功');
    },
  });
};

// 辅助函数
const getOperationTypeColor = (type: string) => {
  const colors = {
    LOGIN: 'green',
    LOGOUT: 'blue',
    CREATE: 'cyan',
    EDIT: 'orange',
    DELETE: 'red',
    QUERY: 'purple',
    EXPORT: 'geekblue',
    PERMISSION_CHANGE: 'magenta',
  };
  return colors[type as keyof typeof colors] || 'default';
};

const getOperationTypeLabel = (type: string) => {
  const labels = {
    LOGIN: '登录',
    LOGOUT: '登出',
    CREATE: '创建',
    EDIT: '编辑',
    DELETE: '删除',
    QUERY: '查询',
    EXPORT: '导出',
    PERMISSION_CHANGE: '权限变更',
  };
  return labels[type as keyof typeof labels] || type;
};

const getStatusColor = (status: string) => {
  const colors = {
    SUCCESS: 'green',
    FAILED: 'red',
    ERROR: 'orange',
  };
  return colors[status as keyof typeof colors] || 'default';
};

const getStatusLabel = (status: string) => {
  const labels = {
    SUCCESS: '成功',
    FAILED: '失败',
    ERROR: '异常',
  };
  return labels[status as keyof typeof labels] || status;
};

onMounted(() => {
  loadLogs();
});
</script>

<template>
  <div class="audit-log">
    <!-- 搜索区域 -->
    <Card title="搜索条件" :bordered="false" style="margin-bottom: 16px">
      <Row :gutter="16">
        <Col :span="6">
          <Form.Item label="关键词">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="请输入用户或描述关键词"
              allow-clear
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="操作类型">
            <Select
              v-model:value="searchForm.operationType"
              placeholder="请选择操作类型"
              allow-clear
              :options="operationTypeOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="用户">
            <Input
              v-model:value="searchForm.user"
              placeholder="请输入用户名"
              allow-clear
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              :options="statusOptions"
            />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col :span="24" style="text-align: right">
          <Space>
            <Button @click="resetSearch">重置</Button>
            <Button type="primary" @click="handleSearch">搜索</Button>
          </Space>
        </Col>
      </Row>
    </Card>

    <!-- 数据表格 -->
    <Card :bordered="false">
      <div class="table-toolbar">
        <Space>
          <Button :disabled="selectedRowKeys.length === 0" @click="batchDelete">
            <IconifyIcon icon="mdi:delete" />
            批量删除
          </Button>
          <Button @click="exportLogs">
            <IconifyIcon icon="mdi:file-export" />
            导出日志
          </Button>
        </Space>
      </div>

      <Table
        :columns="columns"
        :data-source="logList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{
          selectedRowKeys,
          onChange: (keys: any[]) => (selectedRowKeys = keys as string[]),
        }"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operationType'">
            <Tag :color="getOperationTypeColor(record.operationType)">
              {{ getOperationTypeLabel(record.operationType) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                详情
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.audit-log {
  padding: 20px;
}

.table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
